package conn;

/**
 * @author xuweiwei
 * @date 2018/12/12
 */
public class Layout {

    private byte[][] position;
    private int row;
    private int col;
    public static final byte BLANK = 0;
    public static final byte FILL = 1;
    public static final byte HOLE = -1;


    public Layout(int k) {
        this(k,k);
    }

    public Layout(int row, int col) {
        this.row = row;
        this.col = col;
        position = new byte[row][col];
    }

    public Layout(byte[][] position) {
        this.row = position.length;
        this.col = position[0].length;
        this.position = position;
    }


    public Layout clone() {
        Layout layout = new Layout(row, col);
        for (int x = 0; x < row; x++) {
            for (int y = 0; y < col; y++) {
                layout.position[x][y] = this.position[x][y];
            }
        }
        return layout;
    }


    public boolean over() {
        for (int x = 0; x < row; x++) {
            for (int y = 0; y < col; y++) {
                if (this.position[x][y] == BLANK) {
                    return false;
                }
            }
        }
        return true;
    }

    public int countSinglePoint(int startX, int startY) {
        int count = 0;
        position[startX][startY] = BLANK;
        for (int x = 0; x < row; x++) {
            for (int y = 0; y < col; y++) {
                if (position[x][y] != BLANK || x == startX && y == startY) {
                    continue;
                }
                if (single(x, y)) {
                    count++;
                }
            }
        }
        position[startX][startY] = FILL;
        return count;
    }

    public boolean single(int x, int y) {
        int conn = 0;
        if (x + 1 < row && position[x + 1][y] == BLANK) {
            conn++;
        }
        if (y + 1 < col && position[x][y + 1] == BLANK) {
            conn++;
        }

        if (x > 0 && position[x - 1][y] == BLANK) {
            conn++;
        }
        if (y > 0 && position[x][y - 1] == BLANK) {
            conn++;
        }
        return conn <= 1;
    }

    public void display() {
        for (int x = 0; x < row; x++) {
            for (int y = 0; y < col; y++) {
                byte curr = position[x][y];
                System.out.print(BLANK == curr ? '$' : FILL == curr ? 'x' : '*');
            }
            System.out.println();
        }
    }

    public byte see(int x, int y) {
        if (x >= row || x < 0 || y < 0 || y >= col) {
            return HOLE;
        }
        return position[x][y];
    }

    public void fill(int x, int y) {
        position[x][y] = FILL;
    }

    public void setBlank(int x, int y) {
        position[x][y] = BLANK;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }
}
